package com.example.goodsserver.service;

import com.example.goodsserver.dao.GoodsDao;
import com.example.goodsserver.dao.GoodsStockDao;
import com.example.goodsserver.utils.LeafUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private GoodsStockDao goodsStockDao;

    @Autowired
    private RedissonClient redissonClient;

    @Transactional
    public Boolean deductGoodsStock(Long goodsId, Integer quantity) {
        RLock lock = redissonClient.getLock("stock" + goodsId);
        lock.lock();
        try {
            //需要先根据商品id查询是否存在该商品
            Map<String, Object> stringObjectMap = goodsDao.queryGoodsById(goodsId);
            //根据商品Id查询商品的库存，判断商品库存是否足够
            if (stringObjectMap == null) {
                return false;
            }
            //如果够。就去扣减库存。
            Integer stock = goodsStockDao.queryStockByGoodsId(goodsId);
            if (stock < quantity) {
                return false;
            }
            goodsStockDao.updateStockQuantityByGoodsId(stock - quantity, goodsId);
            return true;
        } finally {
            lock.unlock();
        }
    }

    public String addGoods(Integer quantity, Integer price, String name) {
        Long goodsId = LeafUtil.getLeafId("goods");
        Integer result = goodsDao.insertGoods(goodsId, name, price);
        if (result <= 0) {
            return "商品添加失败";
        }

        Integer goodsStockResult = goodsStockDao.insertGoodsStock(LeafUtil.getLeafId("goods_stock"), goodsId, quantity);
        if (goodsStockResult > 0) {
            return "商品添加成功";
        }

        return "商品添加失败";
    }
}